# -*- coding: utf-8 -*-
import requests,base64,json
from Crypto.Cipher import AES,DES
from Crypto.Util.Padding import pad
from lxml import etree
import random
class DailyTask_Submit():
    key = ""
    exexution = ""
    DESkey = "b3L26XNL" #hook某日校园app得到
    iv = "AQIDBAUGBwg="
    session = requests.session()
    loginmessage = ""
    headers = {
        "User-Agent": "Mozilla/5.0 (Linux; Android 10; Redmi Note 4 Build/QQ3A.200805.001; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/87.0.4280.101 Mobile Safari/537.36  cpdaily/8.2.17 wisedu/8.2.17"
    }
    url = "https://ids.henu.edu.cn/authserver/login?service=https://henu.campusphere.net/wec-counselor-sign-apps/stu/mobile/index.html"
    def __init__(self,sno,pwd):
        '''

        :param sno:学号
        :param pwd: 密码
        '''
        self.initloginparam()
        self.loginmessage = self.login(sno,pwd)
        print(self.loginmessage)
    def initloginparam(self):#获取登录参数execution和AES加密秘钥
        ret  =self.session.get(self.url,headers=self.headers).text
        html = etree.HTML(ret) #实例化etree对象
        self.key = html.xpath('''//*[@id="pwdEncryptSalt"]/@value''')[0]#利用xpath解析html,获取pwdEncryptSalt(AES秘钥)
        self.exexution = html.xpath('''//input[@name="execution"]/@value''')[0]#利用xpath解析html,execution
    def login(self,sno,pwd):
        data = {
            "username":sno,
            "password":self.Encrypt(pwd),
            "captcha":"",
            # "rememberMe":"true",
            "_eventId":"submit",
            "cllt":"userNameLogin",
            "lt":"",
            "execution":self.exexution
        }
        # print(self.Encrypt(pwd))
        ret = self.session.post(url=self.url,data=data,headers=self.headers)
        html = etree.HTML(ret.text)
        if ret.status_code == 401:
            return html.xpath('''//div[@class="main"]/form/div[@id="formErrorTip2"]/span/text()''')#获取登录失败原因（密码错误或需要验证码）
        if ret.status_code==500:
            return "internal error,please wait for some time and try again"
        return "Login Successfully"
    def AESEncrypt(self,key,pwd):
        data = "y6dDDj4dKssfNpNiXX7cKzC3EixhJ3mW7w62a4hEyTHyfTmExteYpm4P2NhBMxhM"+pwd
        iv = "xPGFZtcz8RMES5K5".encode("utf-8")
        aes = AES.new(key=key.encode("utf-8"),iv=iv,mode=AES.MODE_CBC)
        data = pad(data.encode("utf-8"),aes.block_size,"pkcs7")
        s = base64.b64encode(aes.encrypt(data))
        return s.decode("utf-8")
    def Encrypt(self,pwd):
        return self.AESEncrypt(key = self.key,pwd=pwd)
    def getTaskinfo(self):

        self.headers.update({"Content-Type": "application/json;charset=UTF-8"})
        data = {
        }
        ret = self.session.post("https://henu.campusphere.net/wec-counselor-sign-apps/stu/sign/getStuSignInfosInOneDay",data=json.dumps(data),headers=self.headers).text
        try:
            dictavar  =  json.loads(ret)['datas']['unSignedTasks'][0]
        except:
            return "no unsigned task"
        return dictavar

        # row = list(["rows"])
        # for i in row:
            # print(i)
    def getTaskdetail(self):

        dictvar = self.getTaskinfo()
        if dictvar=="no unsigned task":
            return "no unsigned task"
        data = {
            "signInstanceWid":dictvar["signInstanceWid"],
            "signWid":dictvar["signWid"]
        }
        # ret =self.session.post("https://henu.campusphere.net/wec-counselor-sign-apps/stu/sign/detailSignInstance",headers=self.headers, data=json.dumps(data)).text

        ret = self.session.post("https://henu.campusphere.net/wec-counselor-sign-apps/stu/sign/detailSignInstance",headers=self.headers,data=json.dumps(data)).text
        print(ret)
        return ret
    def submit_form(self,longitude,latitude,position):
        '''

        :param longitude:经度
        :param latitude: 纬度
        :param position: 位置
        :return:
        '''
        if self.loginmessage != "Login Successfully":
            return self.loginmessage
        s  = self.getTaskdetail()
        if s == "no unsigned task":
            return s
        form = {"longitude": longitude,
              "latitude": latitude,
              "isMalposition": 1,
              "abnormalReason": "",
              "signPhotoUrl": "",
              "isNeedExtra": 1,
              "position": position,
              "uaIsCpadaily": "true",
              "signInstanceWid": json.loads(s)["datas"]['signInstanceWid'],
              "extraFieldItems": [
                  {"extraFieldItemValue": json.loads(s)["datas"]["extraField"][0]["extraFieldItems"][0]['content'],
                   "extraFieldItemWid": json.loads(s)["datas"]["extraField"][0]["extraFieldItems"][0]['wid']},
                  {"extraFieldItemValue": json.loads(s)["datas"]["extraField"][1]["extraFieldItems"][0]['content'],
                   "extraFieldItemWid": json.loads(s)["datas"]["extraField"][1]["extraFieldItems"][0]['wid']},
                  {"extraFieldItemValue": "A:否",
                   "extraFieldItemWid": json.loads(s)["datas"]["extraField"][2]["extraFieldItems"][0]['wid']},
                  {"extraFieldItemValue": "A:否",
                   "extraFieldItemWid": json.loads(s)["datas"]["extraField"][3]["extraFieldItems"][0]['wid']}
              ]}
        self.session.headers.update({
            'Cpdaily-Extension':self.generate_Cpdaily_Extension(longitude,latitude)
        })
        ret = self.session.post('https://henu.campusphere.net/wec-counselor-sign-apps/stu/sign/submitSign',headers=self.headers,data=json.dumps(form))
        print(ret.text)
        return json.loads(ret.text)['message']
    def generate_Cpdaily_Extension(self,longitude,latitude):
        raw = json.dumps({"systemName":"android",
               "systemVersion":"10",#系统版本
               "model":"Redmi Note 4",#手机型号
               "deviceId":self.RandomDeviceid()+"XiaomiRedmiNote4",#可以生成16位随机值加上手机型号
               "appVersion":"8.2.17",#系统版本
               "lon":longitude,#经度
               "lat":latitude,#纬度
               "userId":"666666"#学号，不检测
               })
        return self.DES_CBC_PKcs5Padding(raw)
    def DES_CBC_PKcs5Padding(self,data):
        ciper = DES.new(self.DESkey.encode('utf-8'),mode=DES.MODE_CBC,iv=base64.b64decode(self.iv))
        data = data.encode("utf-8")
        data  = pad(data,DES.block_size,"pkcs7")#进行pkcs7填充
        return base64.b64encode(ciper.encrypt(data)).decode("utf-8")
    def RandomDeviceid(self):
        str = "qwertyuioplkjhgfdsazxcvbnm1234567890"
        de = ""
        for  i in range(0,16):
            de+=str[random.randint(0,35)]
        return de
    #serve酱云函数调用609错误，暂未解决
    # def servesend(self,skey,mes):
    #     print("Serve酱推送开始")
    #     data = {
    #         'text':'今日校园签到',
    #         'desp':mes
    #     }
    #
    #     url = "https://sc.ftqq.com/{0}.send".format(skey)
    #     ret = json.loads(requests.post(url,data=data).text)
    #     if ret['errmsg']=="success":
    #         print("推送成功")
    #     else:
    #         print("推送失败，原因"+ret['errmsg'])
    def pushplussend(self, token, mes):
        if self.loginmessage != "Login Successfully":
            return self.loginmessage
        print("push+推送开始")
        data = {
            'title': '今日校园签到',
            'content': mes
        }
        #http://pushplus.hxtrip.com/send?token=90bfcf81bf8342a2a72657baddd6b1dc&title=XXX&content=XXX&template=h
        url = "http://pushplus.hxtrip.com/send?token="+token
        ret = json.loads(requests.get(url, params=data, headers=self.headers).text)
        print(ret)
        if ret['msg'] == "请求成功":
            print("推送成功")
        else:
            print("推送失败，原因" + ret['data'])

